package com.mdlaser.config;


import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.mdlaser.util.UserUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * 数据库公共字段自动填充
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        setTimeFile(metaObject, "createTime");
        setTimeFile(metaObject, "updateTime");
        if (UserUtil.getCurrentUserSafe() != null) {
            this.setFieldValByName("updateUser", UserUtil.getCurrentUserSafe().getId(), metaObject);
            this.setFieldValByName("createUser", UserUtil.getCurrentUserSafe().getId(), metaObject);
        }
    }


    @Override
    public void updateFill(MetaObject metaObject) {
        setTimeFile(metaObject, "updateTime");
        if (UserUtil.getCurrentUserSafe() != null) {
            this.setFieldValByName("updateUser", UserUtil.getCurrentUserSafe().getId(), metaObject);
        }

    }

    private void setTimeFile(MetaObject metaObject, String timeFiled) {
        Class<?> setterType;
        try {
            setterType = metaObject.getSetterType(timeFiled);
        } catch (Exception e) {
            return;
        }
        if (setterType == LocalDateTime.class) {
            this.setFieldValByName(timeFiled, LocalDateTime.now(), metaObject);
        } else if (setterType == Date.class) {
            this.setFieldValByName(timeFiled, new Date(), metaObject);
        }
    }
}